<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Todo List</title>
  <link rel="stylesheet" href="../js/nprogress/nprogress.css">
  <link rel="stylesheet" href="assets/css/index.css">
  <link rel="stylesheet" href="">
</head>

<body>
  <section class="todoapp">
    <header class="header">
      <h1>todos</h1>
      <input id="task" class="new-todo" placeholder="What needs to be done?" autofocus>
    </header>
    <!-- This section should be hidden by default and shown when there are todos -->
    <section class="main">
      <input class="toggle-all" type="checkbox">
      <label for="toggle-all">Mark all as complete</label>
      <ul class="todo-list" id="todo-list">

      </ul>
    </section>
    <!-- This footer should hidden by default and shown when there are todos -->
    <footer class="footer">
      <!-- This should be `0 items left` by default -->
      <span class="todo-count"><strong>0</strong> item left</span>
      <!-- Remove this if you don't implement routing -->
      <ul class="filters">
        <li>
          <a href="#/">All</a>
        </li>
        <li>
          <a href="#/active">Active</a>
        </li>
        <li>
          <a href="#/completed">Completed</a>
        </li>
      </ul>
      <!-- Hidden if no completed items are left ↓ -->
      <button class="clear-completed">Clear completed</button>
    </footer>
  </section>
  <script src="/js/jquery.min.js"></script>
  <script src="/js/template-web.js"></script>
  <script src="../js/nprogress/nprogress.js"></script>
  <script type="text/html" id="tpl">
    {{each tasks}}
    <li class="{{$value.completed==true?'completed':''}}">
      <div class="view">
        <input class="toggle" type="checkbox" {{$value.completed==true?'checked':''}}>
        <label>{{$value.title}}</label>
        <button class="destroy" data-id="{{$value._id}}"></button>
      </div>
      <input class="edit" value="Rule the web">
    </li>
    {{/each}}
  </script>
  <script>
    $(document).ajaxStart(function() {
      NProgress.start();
    }).ajaxComplete(function() {
      NProgress.done();
    })
    // editing类名的作用??
    // completed 类名的作用??
    //请求数据，然后渲染页面
    var taskAry = [];//全局
    var taskBox = $('#todo-list');
    // setTimeout
    $.ajax({
      type: 'get',//get或post
      url: '/todo/task',//请求的地址
      data: {},//如果不需要传，则注释掉 请求的参数，a=1&b=2或{a:1,b:2}或者jq中的serialize方法，或者formData收集
      dataType: 'json',
      success: function(result) {//成功的回调函数
        taskAry = result;
        console.log(result)
        render()
      }
    })

    //获取添加文本框
    var taskInp = $('#task');
    taskInp.on('keyup', function(event) {
      if(event.keyCode == 13) {
        var taskName = this.value.trim();
        // var taskName = $(this).val().trim();
        if(taskName == "") {
          alert('任务不能为空');
          return;
        }
        $.ajax({
          type: 'post',//get或post
          url: '/todo/addTask',//请求的地址
          contentType: 'application/json',
          data: JSON.stringify({
            title: taskName
          }),
          dataType: 'json',
          success: function(result) {//成功的回调函数
            //再一次发送ajax请求拿数据
            taskAry.push(result);
            render()
            taskInp.val('');
          }
        })
      }
    })

    // $('.destroy').on('click',function(){
    //   console.log(123)
    // })

    //事件委托
    taskBox.on('click', '.destroy', function() {
      // console.log(this.getAttribute('data-id'))
      // console.log($(this).attr('data-id'))
      var id = $(this).attr('data-id');
      $.ajax({
        type: 'get',//get或post
        url: '/todo/deleteTask',//请求的地址
        data: { _id: id },//如果不需要传，则注释掉 请求的参数，a=1&b=2或{a:1,b:2}或者jq中的serialize方法，或者formData收集
        dataType: 'json',
        success: function(result) {//成功的回调函数
          console.log(result)
          //item是我们taskAry在遍历的时候每一项
          // taskAry.forEach(function(item){

          // })
          //result拿到的是当前删除的这一项的对象
          //item是taskAry每次遍历得到的对象
          var index = taskAry.findIndex(item => item._id == result._id);
          taskAry.splice(index, 1);//根据id值把当前删除的这一项移除
          render()
        }
      })
    })

    //删除功能
    taskBox.on('change', '.toggle', function() {
      //得到的是一个布尔值,如果当前被选中，则是true 否则是false
      var status = $(this).is(':checked');
      // console.log(status);
      var id = $(this).siblings('button').attr('data-id');
      // console.log(id)
      $.ajax({
        type: 'post',//get或post
        url: '/todo/modifyTask',//请求的地址
        contentType: 'application/json',
        data: JSON.stringify({ _id: id, completed: status }),//如果不需要传，则注释掉 请求的参数，a=1&b=2或{a:1,b:2}或者jq中的serialize方法，或者formData收集
        dataType: 'json',
        success: function(result) {//成功的回调函数
          // console.log(result)
          //第一步、找到修改了状态的这一项对象
          var task = taskAry.find(item => item._id == result._id);
          task.completed = result.completed;
          render();
        }
      })
    })


    //双击修改任务名称
    taskBox.on('dblclick', 'label', function() {
      console.log(123)
      //找到当前这一个label对应的li，给它添加一个类名editing
      var li = $(this).parent().parent();
      li.addClass('editing');
      //获取当前选中的这个label的值
      var title = $(this).html();
      var input = li.find('.edit');
      input.val(title);
      input.focus();
    })

    //用中文描述出来
    //当input失去焦点的时候，保存修改的内容
    taskBox.on('blur', '.edit', function() {
      //找当前这个input对应的li
      var li = $(this).parent();
      //再通过li找button
      var btn = li.find('button');
      //在button中找自定义属性data-id
      var id = btn.attr('data-id');
      console.log(id);
      //当前修改之后任务名称
      var taskName = $(this).val();


      $.ajax({
        type: 'post',//get或post
        url: '/todo/modifyTask',//请求的地址
        contentType: 'application/json',
        data: JSON.stringify({
          _id: id,
          title: taskName
        }),//如果不需要传，则注释掉 请求的参数，a=1&b=2或{a:1,b:2}或者jq中的serialize方法，或者formData收集
        dataType: 'json',
        success: function(result) {//成功的回调函数
          console.log(result)
          //找到了taskAry这个数组中被修改了任务名称的值对应对象
          var task = taskAry.find(item => item._id == result._id)
          task.title = result.title
          render();
        }
      })
    })

    //清除已完成
    $('.clear-completed').on('click', function() {
      $.ajax({
        type: 'get',//get或post
        url: '/todo/clearTask',//请求的地址
        success: function(result) {//成功的回调函数
          // console.log(result)
          if(result.deletedCount > 0) {
            taskAry = taskAry.filter(item => item.completed == false);
            render();
          }
        }
      })
    })

    window.onhashchange = function() {
      render();
    }


    function render() {
      var tasks = [];
      var current = location.hash;
      switch(current) {
        case '#/':
          tasks = taskAry;
          $('.filters a').removeClass('selected');
          $('.filters a:eq(0)').addClass('selected');
          break;
        case '#/active':
          $('.filters a').removeClass('selected');
          $('.filters a:eq(1)').addClass('selected');
          tasks = taskAry.filter(item => item.completed == false);
          break;
        case '#/completed':
          $('.filters a').removeClass('selected');
          $('.filters a:eq(2)').addClass('selected');
          tasks = taskAry.filter(item => item.completed == true);
          break;
      }
      var html = template('tpl', { tasks: tasks, current: current });
      taskBox.html(html);
      //计算未完成的任务的数量
      $('.todo-count strong').html(taskAry.filter(item => item.completed == false).length)
    }
  </script>
</body>

</html>